package com.controller.cart;

import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.dto.cart.CartDTO;
import com.dto.cart.CartOrderDTO;
import com.model.dao.ChildcatalogTable;
import com.model.dao.ChildcatalogTableDAO;
import com.model.dao.GuestTable;
import com.model.dao.GuestTableDAO;
import com.model.dao.OrderDAO;
import com.model.dao.OrderItemsTable;
import com.model.dao.OrderTable;
import com.model.dao.UserTable;
import com.model.dao.UserTableDAO;

@ManagedBean(name = "checkOutController")
@SessionScoped
public class CheckOutController implements Serializable {

	private static final long serialVersionUID = -5960090905248759640L;
	
	public int createOrder(CartOrderDTO dto) throws Exception{
		OrderDAO dao=new OrderDAO();
		OrderTable table=new OrderTable();
		table.setDateOfOrder(new Date());
		Set<OrderItemsTable> orderItemsTables = new HashSet<OrderItemsTable>(
				0); 
		for(CartDTO var:dto.getItemsList()){
			OrderItemsTable orderItemsTable=new OrderItemsTable();
			ChildcatalogTableDAO dao2=new ChildcatalogTableDAO();
			ChildcatalogTable childcatalogTable= dao2.findById(var.getItemId());
			orderItemsTable.setChildcatalogTable(childcatalogTable);
			orderItemsTable.setOrderTable(table);
			orderItemsTable.setItemQty(Integer.parseInt(var.getQty()));
			orderItemsTables.add(orderItemsTable);
		}
		table.setOrderItemsTables(orderItemsTables);
		table.setOrderStatus("Submitted");
		table.setPrice(dto.getTotal()+"");
		if(!dto.getOrderType().equalsIgnoreCase("G")){
		UserTableDAO dao2 = new UserTableDAO();
		UserTable usertable = dao2.findById(dto.getUserId());
		table.setUserTable(usertable);
		}
		if(dto.getOrderType().equalsIgnoreCase("G")){
		GuestTableDAO dao3=new GuestTableDAO();
		GuestTable guestTable=dao3.findById(dto.getUserId());
		table.setGuestTable(guestTable);
		}
		table.setOrderType(dto.getOrderType());
		return dao.persist(table);
	}

}
